package com.xana.acg.fac.net;


import android.util.ArrayMap;

import com.xana.acg.Factory;
import com.xana.acg.fac.priavte.Account;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.xana.acg.com.Common.HEADER.contentType;
import static com.xana.acg.com.Common.SEVER.bili;

/**
 * 网络请求封装
 */
public class Network {


    private ArrayMap<String, Retrofit> rMap = new ArrayMap<>();

    private static Network ins;
    static {
        ins = new Network();
    }

    private Network() {
    }

    public static Retrofit getRetrofit(String server) {
        if (ins.rMap.containsKey(server)) {
            return ins.rMap.get(server);
        }

        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request req = chain.request();
                        Request.Builder builder = req.newBuilder();
                        String cookie = Account.getCookie();
                        if (cookie != null)
                            builder.addHeader("Cookie", cookie);
                        builder.addHeader("Content-type", contentType);
                        Request request = builder.build();
                        return chain.proceed(request);
                    }
                })
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(server)
                .client(client)
                // 设置 json解析器
                .addConverterFactory(GsonConverterFactory.create(Factory.getGson()))
                .build();

        ins.rMap.put(server, retrofit);
        return retrofit;
    }

    /**
     * 返回一个网络请求代理
     *
     * @return
     */
    public static Api remote(String server) {
        return getRetrofit(server).create(Api.class);
    }

    public static BiliAPI biliAPI(){
        return getRetrofit(bili).create(BiliAPI.class);
    }

}
